package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_LIST_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> getTypeList() {
        //1.从redis中查询缓存
        String listJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_LIST_KEY);

        //2.判断是否存在
        if (listJson != null){
            //3.存在，直接返回
            return JSONUtil.toList(listJson,ShopType.class);
        }

        //4.不存在，从数据库中查询
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        if (shopTypes == null){
            //5.不存在，返回错误
            return null;
        }

        //6.存在，写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_LIST_KEY,JSONUtil.toJsonStr(shopTypes));

        //7.返回
        return shopTypes;
    }
}
